'use strict';

const xtpl = require('xtpl');
const path = require('path');
const md5 = require('md5');
const mysql = require('../configs/database.js');
const baseCtr = require('./baseController.js');


const captchapng = require('captchapng');	// 验证码图片
//邮箱发送验证码
const  nodemailer = require("nodemailer");
const smtpTransport = require('nodemailer-smtp-transport');
const wellknown = require("nodemailer-wellknown");
const config = wellknown("QQ");

config.auth = {
	user: '3176027419@qq.com',
	pass: 'jnikugrszpizdhef',	// 授权码
}

module.exports.main = function(req, res){
	//查询表总数
	var total = function(t,w){
		return new Promise(function (resolve,reject) {
			mysql.table(t).count(w).then(function(num){
				resolve(num);
			}).catch(function(err){
				reject(err);
			});
		});
	}

	var sublist = new Promise(function (resolve,reject) {
			var data = [];
			mysql.query('select ss.sub_id,s.sub_name,count(ss.stu_id) as snum from pre_student_subject_data as ss left join pre_subject as s on ss.sub_id=s.sub_id group by ss.sub_id order by snum desc',data).then(function(sub_data){
				resolve(sub_data);
			}).catch(function(err){
				reject(err);
			});
		});

	var p1 = total('class','class_id');
	var p2 = total('student','stu_id');
	var p3 = total('subject','sub_id');
	var p4 = total('admin','admin_id');

	//执行多个异步任务，
	Promise.all([p1,p2,p3,p4,sublist]).then(function(data){
		// console.log(data);
	    xtpl.renderFile(
			path.join(__dirname,'../views/admin/main_index.html'),
			{
				page:'index',
				clsNum: data[0],
				stuNum: data[1],
				subNum: data[2],
				adminNum: data[3],
				subList: data[4],
			},
			function(err,content){
				res.setHeader('Content-Type','text/html;charset=utf-8');
				res.send(content);
			}
		);
	}, function (err) {
	  //then第二个函数是失败的回调函数，参数是reject(err)中的err错误对象
	  console.log('失败：' + err);
	}).catch((error) => {
	  console.log(error)
	});
}

module.exports.register = function(req, res){
	xtpl.renderFile(
		path.join(__dirname,'../views/admin/register.html'),
		{},
		function(err,content){
			res.setHeader('Content-Type','text/html;charset=utf-8');
			res.send(content);
		}
	)
}

module.exports.registerData = function(req, res){
	mysql.table('admin').where({admin_name:req.body.email}).find().then(function(result){
		if(JSON.stringify(result)=='{}'){

			// 增加多一步：验证码验证
			console.log(req.signedCookies.code);//获取特定cookie值
			if(req.signedCookies.code==undefined){
				res.send(JSON.stringify({error:1,msg:'验证码已过期，请重新发送'}));
				return false;
			}

			if(req.signedCookies.code!=req.body.code){
				res.send(JSON.stringify({error:1,msg:'验证码错误'}));
				return false;
			}

			var data = {
					admin_name: req.body.email,
					admin_pwd: md5(req.body.pwd),
					admin_time: (new Date().getTime())/1000
				}

			mysql.table('admin').add(data).then(function(){
					res.send(JSON.stringify({error:0,msg:'注册成功'}));
					// console.log('注册成功');
				}).catch(function(err){
					console.log(err);
				});

		}else{
			res.send(JSON.stringify({error:1,msg:'该邮箱已注册'}));
		}
	})
}

module.exports.login = function(req, res){
	xtpl.renderFile(
		path.join(__dirname,'../views/admin/login.html'),
		{},
		function(err,content){
			res.setHeader('Content-Type','text/html;charset=utf-8');
			res.send(content);
		}
	);
}

// 登录操作
module.exports.loginData = function(req,res){

	// 增加多一步：图片验证码验证
	if(req.session.imgcode != req.body.code){
		res.send(JSON.stringify({error:1,msg:'验证码错误'}));
		return false;
	}

	mysql.table('admin').where({admin_name:req.body.email,admin_pwd:md5(req.body.pwd)}).find().then(function(result){
		if(JSON.stringify(result)!='{}'){
			// 把邮箱记录到session里面
			req.session.email = req.body.email;
			res.send(JSON.stringify({error:0,msg:'登录成功'}))
		}else{
			res.send(JSON.stringify({error:1,msg:'邮箱或密码错误'}))
		}
	});
}

// 给邮箱发送验证码
module.exports.sendCode = function(req,res){
	var email = req.body.email;
	mysql.table('admin').where({admin_name:req.body.email}).find().then(function(result){
		if(JSON.stringify(result)=='{}'){
			// 获取随机数(验证码)
			var code = baseCtr.randomString();
			res.cookie("code",code,{maxAge:1*60*1000,signed:true}); //设置cookie和过期时间

			// 发送操作
			var transporter = nodemailer.createTransport(smtpTransport(config));
			var mailOptions = {
			    from:"lin~<3176027419@qq.com>",  // 发件人
			    to:email,	// 收件人
			    subject:"注册账号",	// 标题
			    text:"text plain",	// 文本(忽略)
			    html:"<div>尊敬的用户，您的验证码是：<span style='color:red;'>"+code+"</span></div>"	// 内容
			};
			// 发送方法
			transporter.sendMail(mailOptions, function(error, info){
			    if(error){
			        return console.log(error);
			    }
			    res.send(JSON.stringify({error:0,msg:'发送成功'}))

			});
		}else{
			res.send(JSON.stringify({error:1,msg:'该邮箱已被注册'}));
		}
	})
}

// 图片验证码
module.exports.imgCode = function(req,res){

	var code = parseInt(Math.random() * 9000 + 1000);	// 纯数字
    
    // 使用session记录验证码
    req.session.imgcode = code;
    
    var p = new captchapng(100, 30, code);
    p.color(0,0,0,0);//背景颜色
    p.color(80, 80, 80, 255);
    var img = p.getBase64();
    var imgbase64 = new Buffer(img, 'base64');
    res.writeHead(200, {
        'Content-Type': 'image/png'
    });
    res.end(imgbase64);	//base64文本
}

//退出
module.exports.logout = function(req, res){
	req.session.email = undefined;

	res.redirect('/admin/main/login');
}

module.exports.adminInfo = function(req, res){
	// console.log(req.session.email);
	res.send(req.session.email);
}